import { GameData } from "../Data/GameData";
import Block from "./Block";

/** 卡牌颜色 */
enum cardColor {
    CARD_0 = "#969696",
    CARD_1 = "#C8C8C8",
}

const { ccclass, property } = cc._decorator;

@ccclass
export default class Grid extends cc.Component {
    /** 选中框节点 */
    @property(cc.Node)
    select: cc.Node = null;
    @property(cc.Sprite)
    Sprite_main: cc.Sprite = null;
    // @property(cc.Node)
    // X: cc.Node = null;

    id: number = 0;
    x: number = 0;
    y: number = 0;
    block: Block = null;

    canPlace: boolean = true;

    // 初始化
    init(_id: number, _x: number, _y: number) {
        this.id = _id;
        this.x = _x;
        this.y = _y;
        this.block = null;

        // const colorIndes = (((this.y + 1) % 2) + ((this.x + 1) % 2)) % 2;
        // this.node.color = new cc.Color().fromHEX(cardColor["CARD_" + colorIndes]);
        this.Sprite_main.node.active = false;

        this.initWidthAndHeight(GameData.cell_width, GameData.cell_height);
        this.initPosition();

        this.Refresh();
        // this.AddListener();
    }

    RefreshPlace() {
        // this.X.active = !this.canPlace;
        // this.X.active = true;
    }

    GetNodeWorldPostation(_node: cc.Node): cc.Vec3 {
        let pos: cc.Vec3 = cc.v3();
        if (_node.parent == null) {
            pos = cc.v3(_node.getPosition());
        } else {
            pos = cc.v3(_node.parent.convertToWorldSpaceAR(_node.getPosition()));
        }
        return pos;
    }

    TOUCH_END() {
        GameData.IsMouseDown = false;
    }

    AddListener() {
        this.node.on(
            cc.Node.EventType.TOUCH_END,
            (t) => {
                this.TOUCH_END();
            },
            this
        );
        this.node.on(
            cc.Node.EventType.TOUCH_CANCEL,
            (t) => {
                this.TOUCH_END();
            },
            this
        );

        this.node.on(cc.Node.EventType.TOUCH_MOVE, (t) => { }, this);

        this.node.on(cc.Node.EventType.TOUCH_START, (t) => { }, this);
    }

    Main() { }

    Refresh() {
        // this.node.active = this.id >= 0;
    }

    Select(select: boolean): void {
        this.select.active = select;
    }

    // 初始化单元宽高
    initWidthAndHeight(cardWidth?: number, cardHeight?: number) {
        if (cardWidth) this.node.width = cardWidth;
        if (cardHeight) this.node.height = cardHeight;
    }

    // 初始化位置
    initPosition() {
        let x = -GameData.W / 2 + this.node.width / 2 + this.node.width * this.x;
        let y = -GameData.H / 2 + this.node.height / 2 + this.node.height * this.y;
        this.node.position = cc.v3(x, y, 0);
    }

    Flash() {
        cc.Tween.stopAllByTarget(this.select);
        cc.tween(this.select)
            .repeatForever(
                cc.tween()
                    .to(0.4, { scale: 0.98 })
                    .to(0.4, { scale: 0.90 })
            )
            .start()
    }
}